package com.pg.agent.engine.service.component;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pg.agent.engine.client.bo.InterfaceBO;
import com.pg.agent.engine.client.model.agent.AIAgent;
import com.pg.agent.engine.client.model.llm.CallLog;
import com.pg.base.component.PgAssert;
import com.pg.base.util.PgHttpUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * API组件
 * @author huhuaping
 * @date 2023/11/15 10:26
 */
@Slf4j
@Data
public class APIComponent implements ToolComponent, Serializable {

    private Long id;
    private String url;
    private String requestMethod;
    private String inParam;
    private String headerParam;
    private String adapterParam;
    private String name;
    private String code;
    private String description;
    /**
     * 查询获取方式
     */
    private Integer argGetWay;
    /**
     * 组件提示词指令
     */
    private String promptContent;

    /**
     * 接口列表
     */
    private String interfaceList;

    private List<InterfaceBO> interfaceBOList;

    /**
     * 接口依赖
     */
    private String elExpress;

    /**
     * 出参类型 1:直接输出至客户端;2:封装为提示词;3:组件入参;4:json;
     */
    private Integer outParamType;

    private String outParam;

    public static void logInfo(CallLog lLMCallLog) {

        log.info("\n{}({})********组件调用信息如下*******\n{}\nparam: {},\n********组件调用结果如下*******\n{} \n***************************结束****************************",
                lLMCallLog.getCallType(), lLMCallLog.getCallName(), lLMCallLog.getSystemPrompt(), lLMCallLog.getUserPrompt(), lLMCallLog.getResponse());

    }

    @Override
    public String func(AIAgent agent, CallLog comCallInfo, String argument) {

        Map<String, Object> inParamMap = agent.getParamMap();
        Map<String, String> headerMap = new HashMap<>();
        Map<String, Object> paramMap = new HashMap<>();
        String result = null;

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("url：" + url);
        stringBuilder.append("\nheader：" + JSON.toJSONString(headerMap));
        if (ObjectUtil.isAllNotEmpty(inParam, inParamMap)) {
            JSONArray jsonArray = JSON.parseArray(inParam);

            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                if (jsonObject.containsKey("paramCode")) {
                    String paramCode = jsonObject.getString("paramCode");
                    paramMap.put(paramCode, inParamMap.get(paramCode));
                }
            }
        }

        try {

            comCallInfo.setCallStartTime(new Date());
            long time = System.currentTimeMillis();

            if (PgHttpUtil.GET.equals(requestMethod)) {
                result = PgHttpUtil.get(url, headerMap, paramMap);
                comCallInfo.setUserPrompt(JSON.toJSONString(paramMap));
            } else {
                result = PgHttpUtil.postBody(url, new HashMap<>(), argument);
                comCallInfo.setUserPrompt(JSON.toJSONString(argument));
            }
            comCallInfo.setCallName(this.name);
            comCallInfo.setSystemPrompt(stringBuilder.toString());
            comCallInfo.setCallEndTime(new Date());
            comCallInfo.setTimeLong(System.currentTimeMillis() - time);
            comCallInfo.setResponse(result);
        } catch (Exception e) {
            PgAssert.bizError(true, 1000, "第三方接口请求出错,原因：" + e.getMessage());
        }
        logInfo(comCallInfo);
        return result;
    }
}
